@tool
@icon("icons/compound_state.svg")
class_name CompoundState
extends State

@export var init_state_path:NodePath
var init_state:State
var cur_state:State
var sub_states:Array[State] = []
var sub_state_dict:Dictionary = {}

func state_init(fsm:FSM):
	super.state_init(fsm)
	for child in get_children():
		if child is State:
			sub_states.append(child)
			sub_state_dict[child.state_name] = child
			child.state_init(fsm)
	init_state = get_node_or_null(init_state_path)
	cur_state = init_state
	if init_state == null:
		push_error("CompoundState " + state_name + " 没有对应的初始State")
func on_enter(from_state:State):
	super.on_enter(from_state)
func on_update(delta:float):
	super.on_update(delta)
	if get_state_status() == GameEnum.StateStatus.Waiting:
		return
	cur_state.on_update(delta)
func on_physics_update(delta:float):
	super.on_physics_update(delta)
	if get_state_status() == GameEnum.StateStatus.Waiting:
		return
	cur_state.on_physics_update(delta)
func on_exit(to_state:State):
	cur_state.on_exit(to_state)
	cur_state = null
	super.on_exit(to_state)
func get_state_status() -> GameEnum.StateStatus:
	if cur_state_status == GameEnum.StateStatus.Closed and init_state.get_state_status() == GameEnum.StateStatus.Ready:
		cur_state_status = GameEnum.StateStatus.Ready
	return cur_state_status
func translate_state(st_state:State,to_state:State,st_state_path:Array[State],to_state_path:Array[State]):
	var st_state_temp:State = st_state_path.pop_back()
	var to_state_temp:State = to_state_path.pop_back()
	if not st_state_temp:
		if to_state_temp:
			on_enter(st_state)
			cur_state = to_state_temp
			cur_state.translate_state(st_state,to_state,st_state_path,to_state_path)
		else:
			on_enter(st_state)
			cur_state = init_state
			cur_state.translate_state(st_state,to_state,st_state_path,to_state_path)
	else:
		if to_state_temp:
			if st_state_temp.state_name == to_state_temp.state_name:
				to_state_temp.translate_state(st_state,to_state,st_state_path,to_state_path)
			else:
				cur_state.on_exit(to_state)
				cur_state = to_state_temp
				cur_state.translate_state(st_state,to_state,st_state_path,to_state_path)
		else:
			if sub_states.has(st_state_temp):
				cur_state.on_exit(to_state)
			cur_state = init_state
			cur_state.translate_state(st_state,to_state,st_state_path,to_state_path)
func _get_configuration_warnings() -> PackedStringArray:
	var warnings = super._get_configuration_warnings()
	var child_count:int = 0
	for child in get_children():
		if child is State:
			child_count += 1
	if child_count < 1:
		warnings.append("CompoundState" + "至少需要1个State作为初始State")
	elif child_count < 2:
		warnings.append("CompoundState" + "至少需要两个State才有效，如果只需要一个State，建议不使用CompoundState")
	var temp_init_state = get_node_or_null(init_state_path)
	if not temp_init_state:
		warnings.append("初始State找不到")
	elif temp_init_state.get_parent() != self:
		warnings.append("初始State必须是当前CompoundState的直接子节点")
	return warnings
